<template>
  <div class="dingding-container">
    <!-- 头部区域 -->
    <div class="dingding-header">
      <div class="header-content">
        <div class="logo-section">
          <img src="@/assets/钉钉.svg" alt="钉钉Logo" class="dingding-logo" />
          <div class="title-section">
            <h1 class="main-title">钉钉消息推送</h1>
            <p class="subtitle">快速发送消息到钉钉群聊</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 发送消息卡片 -->
      <el-card class="message-card" shadow="hover">
        <div slot="header" class="card-header">
          <i class="el-icon-s-promotion"></i>
          <span>发送消息</span>
        </div>

        <el-form :model="form" label-width="140px" class="dingding-form">
          <!-- 机器人选择 -->
          <el-form-item label="选择机器人" class="bot-select-item">
            <div class="bot-select-container">
              <el-select
                v-model="selectedBotId"
                placeholder="请选择机器人"
                class="bot-select"
                @change="onBotChange"
              >
                <el-option
                  v-for="bot in botList"
                  :key="bot.id"
                  :label="
                    bot.name + '（' + bot.webhook.slice(0, 12) + '...' + '）'
                  "
                  :value="bot.id"
                >
                  <div class="bot-option">
                    <span class="bot-name">{{ bot.name }}</span>
                    <div class="bot-actions">
                      <el-button
                        type="text"
                        size="mini"
                        @click.stop="renameBot(bot.id)"
                        class="action-btn"
                      >
                        <i class="el-icon-edit"></i>
                      </el-button>
                      <el-button
                        type="text"
                        size="mini"
                        @click.stop="deleteBot(bot.id)"
                        class="action-btn delete-btn"
                      >
                        <i class="el-icon-delete"></i>
                      </el-button>
                    </div>
                  </div>
                </el-option>
              </el-select>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-plus"
                @click="addBot"
                class="add-bot-btn"
              >
                新增机器人
              </el-button>
            </div>
          </el-form-item>

          <!-- Webhook配置 -->
          <el-form-item label="Webhook" class="webhook-item">
            <div class="webhook-container">
              <el-input
                v-model="form.webhook"
                placeholder="请输入钉钉群机器人Webhook地址"
                class="webhook-input"
              />
              <el-button
                type="success"
                size="small"
                icon="el-icon-check"
                @click="saveOrUpdateBot"
                class="save-webhook-btn"
              >
                保存配置
              </el-button>
            </div>
          </el-form-item>

          <!-- 消息类型和@所有人 -->
          <div class="message-options">
            <el-form-item label="消息类型" class="msg-type-item">
              <el-select
                v-model="form.msgType"
                placeholder="请选择消息类型"
                class="msg-type-select"
              >
                <el-option label="文本消息" value="text">
                  <i class="el-icon-document"></i>
                  <span style="margin-left: 8px">文本</span>
                </el-option>
                <el-option label="Markdown" value="markdown">
                  <i class="el-icon-edit-outline"></i>
                  <span style="margin-left: 8px">Markdown</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="@所有人" class="at-all-item">
              <el-switch
                v-model="form.atAll"
                active-text="是"
                inactive-text="否"
                active-color="#409EFF"
              />
            </el-form-item>
          </div>

          <!-- 消息内容 -->
          <el-form-item label="消息内容" class="message-content-item">
            <el-input
              type="textarea"
              v-model="form.message"
              :rows="6"
              placeholder="请输入要发送的消息内容"
              class="message-textarea"
              resize="none"
            />
            <div class="message-tips">
              <i class="el-icon-info"></i>
              <span
                >支持文本和Markdown格式，@所有人功能会自动在消息末尾添加</span
              >
            </div>
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item class="action-buttons">
            <el-button
              type="primary"
              :loading="loading"
              icon="el-icon-s-promotion"
              @click="sendMessage"
              class="send-btn"
              size="medium"
            >
              发送消息
            </el-button>
            <el-button
              @click="resetForm"
              icon="el-icon-refresh"
              class="reset-btn"
              size="medium"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 结果提示 -->
      <el-alert
        v-if="resultMsg"
        :title="resultMsg"
        :type="resultType"
        show-icon
        class="result-alert"
        :closable="false"
      />

      <!-- 发送历史卡片 -->
      <el-card class="history-card" shadow="hover">
        <div slot="header" class="card-header">
          <i class="el-icon-time"></i>
          <span>发送历史</span>
          <el-button
            v-if="history.length"
            type="text"
            size="mini"
            @click="history = []"
            class="clear-history-btn"
          >
            清空历史
          </el-button>
        </div>

        <div v-if="history.length" class="history-content">
          <el-timeline>
            <el-timeline-item
              v-for="(item, idx) in history"
              :key="idx"
              :timestamp="item.time"
              :color="item.success ? '#67C23A' : '#F56C6C'"
              :icon="item.success ? 'el-icon-success' : 'el-icon-error'"
              class="history-item"
            >
              <div class="history-content-wrapper">
                <div class="history-meta">
                  <el-tag
                    size="mini"
                    :type="item.msgType === 'markdown' ? 'success' : 'info'"
                    class="msg-type-tag"
                  >
                    {{ item.msgType === "markdown" ? "Markdown" : "文本" }}
                  </el-tag>
                  <el-tag
                    size="mini"
                    v-if="item.atAll"
                    type="warning"
                    class="at-all-tag"
                  >
                    @所有人
                  </el-tag>
                  <span class="webhook-preview"
                    >{{ item.webhook.slice(0, 20) }}...</span
                  >
                </div>
                <div class="history-message">{{ item.message }}</div>
                <div class="history-actions">
                  <el-button
                    type="text"
                    size="mini"
                    @click="copyMsg(item.message)"
                    class="action-btn"
                  >
                    <i class="el-icon-document-copy"></i> 复制
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="resendMsg(item)"
                    class="action-btn"
                  >
                    <i class="el-icon-refresh"></i> 重发
                  </el-button>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>

        <div v-else class="empty-history">
          <i class="el-icon-chat-dot-round"></i>
          <p>暂无发送历史</p>
          <span>发送消息后会在这里显示历史记录</span>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { sendDingTalkMsg } from "@/api/dingding";
export default {
  name: "DingDingLink",
  data() {
    return {
      form: {
        webhook: "",
        msgType: "text",
        atAll: false,
        message: "",
      },
      loading: false,
      resultMsg: "",
      resultType: "success",
      history: [],
      botList: [], // 多机器人列表
      selectedBotId: "", // 当前选中的机器人id
    };
  },
  methods: {
    async sendMessage() {
      if (!this.form.webhook || !this.form.message) {
        this.resultMsg = "Webhook地址和消息内容不能为空";
        this.resultType = "warning";
        return;
      }
      let sendMsg = this.form.message;
      if (
        this.form.msgType === "markdown" &&
        this.form.atAll &&
        !/[@＠]所有人/.test(sendMsg)
      ) {
        sendMsg = sendMsg + "\n\n@所有人";
      }
      this.loading = true;
      this.resultMsg = "";
      try {
        // 调用前端API方法
        const res = await sendDingTalkMsg({
          webhook: this.form.webhook,
          message: sendMsg,
          msgType: this.form.msgType,
          atAll: this.form.atAll,
        });
        if (res && res.success) {
          this.resultMsg = "消息发送成功";
          this.resultType = "success";
          this.addHistory(true);
        } else {
          this.resultMsg = res && res.msg ? res.msg : "消息发送失败";
          this.resultType = "error";
          this.addHistory(false);
        }
      } catch (e) {
        this.resultMsg = "请求失败，请检查网络或Webhook地址";
        this.resultType = "error";
        this.addHistory(false);
      } finally {
        this.loading = false;
      }
    },
    resetForm() {
      this.form.message = "";
      this.form.msgType = "text";
      this.form.atAll = false;
      this.resultMsg = "";
    },
    addHistory(success) {
      this.history.unshift({
        webhook: this.form.webhook,
        msgType: this.form.msgType,
        atAll: this.form.atAll,
        message: this.form.message,
        time: new Date().toLocaleString(),
        success,
      });
      if (this.history.length > 10) this.history.pop();
    },
    copyMsg(msg) {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(msg);
        this.$message.success("已复制到剪贴板");
      } else {
        this.$message.warning("浏览器不支持自动复制");
      }
    },
    resendMsg(item) {
      this.form.webhook = item.webhook;
      this.form.msgType = item.msgType;
      this.form.atAll = item.atAll;
      this.form.message = item.message;
      this.sendMessage();
    },
    // 多机器人配置管理相关方法
    loadBots() {
      const botsStr = localStorage.getItem("dingding_bots");
      if (botsStr) {
        try {
          this.botList = JSON.parse(botsStr);
        } catch {
          this.botList = [];
        }
      } else {
        this.botList = [];
      }
    },
    saveBots() {
      localStorage.setItem("dingding_bots", JSON.stringify(this.botList));
    },
    addBot() {
      this.$prompt("请输入机器人名称", "新增机器人", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /.+/,
        inputErrorMessage: "名称不能为空",
      }).then(({ value }) => {
        const id = Date.now().toString();
        const newBot = {
          id,
          name: value,
          webhook: "",
          msgType: "text",
          atAll: false,
        };
        this.botList.push(newBot);
        this.selectedBotId = id;
        this.form.webhook = "";
        this.form.msgType = "text";
        this.form.atAll = false;
        this.saveBots();
      });
    },
    deleteBot(id) {
      this.$confirm("确定要删除该机器人吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.botList = this.botList.filter((bot) => bot.id !== id);
        if (this.selectedBotId === id) {
          this.selectedBotId = "";
          this.form.webhook = "";
          this.form.msgType = "text";
          this.form.atAll = false;
        }
        this.saveBots();
      });
    },
    renameBot(id) {
      const bot = this.botList.find((b) => b.id === id);
      if (!bot) return;
      this.$prompt("请输入新名称", "重命名机器人", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValue: bot.name,
        inputPattern: /.+/,
        inputErrorMessage: "名称不能为空",
      }).then(({ value }) => {
        bot.name = value;
        this.saveBots();
      });
    },
    onBotChange(id) {
      const bot = this.botList.find((b) => b.id === id);
      if (bot) {
        this.form.webhook = bot.webhook;
        this.form.msgType = bot.msgType || "text";
        this.form.atAll = bot.atAll || false;
      }
    },
    saveOrUpdateBot() {
      if (!this.selectedBotId) {
        this.$message.warning("请先选择机器人");
        return;
      }
      if (!this.form.webhook) {
        this.$message.warning("Webhook地址不能为空");
        return;
      }
      let bot = this.botList.find((b) => b.id === this.selectedBotId);
      if (bot) {
        bot.webhook = this.form.webhook;
        bot.msgType = this.form.msgType;
        bot.atAll = this.form.atAll;
        this.$message.success("机器人配置已更新");
      }
      this.saveBots();
    },
    // 保留原有的loadConfig/saveConfig方法用于兼容单机器人老数据
    loadConfig() {
      const configStr = localStorage.getItem("dingding_config");
      if (configStr) {
        try {
          const config = JSON.parse(configStr);
          this.form.webhook = config.webhook || "";
          this.form.msgType = config.msgType || "text";
          this.form.atAll = config.atAll || false;
          this.$message.success("配置已读取");
        } catch {
          this.$message.error("配置读取失败");
        }
      } else {
        this.$message.info("暂无已保存的配置");
      }
    },
    saveConfig() {
      const config = {
        webhook: this.form.webhook,
        msgType: this.form.msgType,
        atAll: this.form.atAll,
      };
      localStorage.setItem("dingding_config", JSON.stringify(config));
      this.$message.success("配置已保存");
    },
  },
  mounted() {
    this.loadBots();
    // 兼容老数据
    if (!this.botList.length) {
      this.loadConfig();
    }
  },
};
</script>

<style scoped>
.dingding-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 0;
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.dingding-header {
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 20px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.header-content {
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 24px;
  display: flex;
  align-items: center;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.dingding-logo {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.dingding-logo:hover {
  transform: scale(1.05);
}

.title-section {
  display: flex;
  flex-direction: column;
}

.main-title {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
}

.subtitle {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #7f8c8d;
  font-weight: 400;
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
  padding: 32px 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 卡片样式 */
.message-card,
.history-card {
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.message-card:hover,
.history-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  padding: 0;
  border-bottom: none;
}

.card-header i {
  color: #667eea;
  font-size: 20px;
}

.clear-history-btn {
  margin-left: auto;
  color: #909399;
}

/* 表单样式 */
.dingding-form {
  padding: 0;
}

.el-form-item {
  margin-bottom: 24px !important;
}

.el-form-item__label {
  font-weight: 600;
  color: #2c3e50;
}

/* 机器人选择样式 */
.bot-select-container {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.bot-select {
  flex: 1;
}

.add-bot-btn {
  white-space: nowrap;
  border-radius: 8px;
}

.bot-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 4px 0;
}

.bot-name {
  font-weight: 500;
}

.bot-actions {
  display: flex;
  gap: 4px;
}

.action-btn {
  padding: 2px 6px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: #f5f7fa;
}

.delete-btn:hover {
  background: #fef0f0;
  color: #f56c6c;
}

/* Webhook配置样式 */
.webhook-container {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.webhook-input {
  flex: 1;
}

.save-webhook-btn {
  white-space: nowrap;
  border-radius: 8px;
}

/* 消息选项样式 */
.message-options {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.msg-type-select {
  width: 100%;
}

/* 消息内容样式 */
.message-textarea {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.message-textarea:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.message-tips {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.message-tips i {
  color: #667eea;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 32px;
}

.send-btn {
  background: #409eff;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.send-btn:hover {
  background: #66b1ff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.reset-btn,
.load-btn {
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 500;
}

/* 结果提示样式 */
.result-alert {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 历史记录样式 */
.history-content {
  max-height: 400px;
  overflow-y: auto;
}

.history-item {
  margin-bottom: 16px;
}

.history-content-wrapper {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border-left: 4px solid #667eea;
}

.history-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.msg-type-tag,
.at-all-tag {
  border-radius: 4px;
}

.webhook-preview {
  font-size: 12px;
  color: #909399;
  font-family: monospace;
}

.history-message {
  font-size: 14px;
  color: #2c3e50;
  line-height: 1.6;
  white-space: pre-wrap;
  margin-bottom: 8px;
  background: white;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.history-actions {
  display: flex;
  gap: 8px;
}

/* 空状态样式 */
.empty-history {
  text-align: center;
  padding: 48px 24px;
  color: #909399;
}

.empty-history i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.empty-history p {
  font-size: 16px;
  margin: 0 0 8px 0;
  color: #606266;
}

.empty-history span {
  font-size: 14px;
  color: #c0c4cc;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    padding: 24px 16px;
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .main-content {
    padding: 16px;
  }

  .message-options {
    grid-template-columns: 1fr;
  }

  .bot-select-container,
  .webhook-container {
    flex-direction: column;
  }

  .action-buttons {
    flex-direction: column;
  }

  .history-meta {
    flex-direction: column;
    align-items: flex-start;
  }
}

@media (max-width: 480px) {
  .main-content {
    padding: 12px;
  }

  .dingding-header {
    padding: 16px 0;
  }

  .main-title {
    font-size: 24px;
  }

  .subtitle {
    font-size: 12px;
  }
}

/* 滚动条样式 */
.history-content::-webkit-scrollbar {
  width: 6px;
}

.history-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.history-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.history-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>